<?php

namespace app\admin\service;

use app\models\UserModel;

/**
 * Class AccountService
 * @package app\admin\service
 */
class AccountService
{
    private $error;

	/**
	 * User: wufeng
	 * Date: 2020/03/21
	 *
	 * @param $mobile
	 * @param $password
	 * @return bool
	 * @throws \think\Exception
	 * @throws \think\exception\DbException
	 */
    public function getCheckLogin($mobile, $password)
    {
        $member = UserModel::get(['mobile' => $mobile]);
        if (!$member) {
            $this->error = '手机号码不存在';
            return false;
        }

        $encodePassword = self::encodePassword($password, $member['salt']);
        if ($member['password'] !== $encodePassword) {
            $this->error = '密码错误';
            return false;
        }

        if ($member['status'] == 0) {
            $this->error = '该用户已被禁用';
            return false;
        }

        if ($member['status'] == -1) {
            $this->error = '该用户已被删除';
            return false;
        }

        $userModel = new UserModel();
        $userModel->save([
            'last_login' => date('Y-m-d H:i:s', time()),
            'last_ip' => get_client_ip()
        ], ['id' => $member['id']]);
        session('user', $member->toArray());
        return true;
    }

    /**
     * 功能:对用户输入的明文密码进行加密(还记不记得csdn的杯具)
     * @param string $password 明文密码
     * @param string $salt 混淆字符串（盐）,防止简单的MD5加密被逆向破解
     * @return string   加密后的密码
     */
    static public function encodePassword($password, $salt)
    {
        $encryptd_password = md5(md5($password) . $salt);

        return substr($encryptd_password, 0, 32);
    }

    public function getError()
    {
        return $this->error;
    }

    /**
     * 修改密码
     * @return array|\think\response\Json
     * @throws \think\exception\DbException
     */
    public function reset_password()
    {
        $user = session('user');
        $users = UserModel::get($user['id']);
        $oldPsd = AccountService::encodePassword(input('password'),$users['salt']);
        if($oldPsd != $users['password']){
            return ['code' => 1, 'msg' => "原密码错误"];
        }
        $userModel = new UserModel();
        $password = AccountService::encodePassword(input('new_psd'),$users['salt']);
        $result = $userModel->where('id',$users['id'])->setField('password',$password);
        if($result !== false){
            return ['code' => 0, 'msg' => "修改成功"];
        }
        return ['code' => 1, 'msg' => "修改失败"];
    }
}